package hu.dobrosi.j2me.net;

import hu.dobrosi.util.StringUtil;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class URL {

	private String urlString;
	private String page;
	private String host;
	private int port = 80;

	public URL(String url) throws MalformedURLException {
		Object[] ss = StringUtil.splitString(url, "/");
		try {
			host = ss[2].toString();
			Object[] hostParts = StringUtil.splitString(host, ":");
			if (hostParts.length > 1) {
				port = Integer.parseInt(hostParts[1].toString());
				host = hostParts[0].toString();
			}
			page = "";
			for (int i = 3; i < ss.length; i++) {
				page += "/" + ss[i];

			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new MalformedURLException();
		}
		urlString = url;
	}

	public String getPage() {
		return page;
	}

	public void setPage(String page) {
		this.page = page;
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public HttpURLConnection openConnection() throws IOException,
			MalformedURLException {
		if (urlString.toLowerCase().startsWith("https://")) {
			return new HttpsURLConnection((HttpConnection) Connector
					.open(urlString));
		}
		return new HttpURLConnection(this);
	}

}
